package bsi.vn.FirstApp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import bsi.vn.Data.ContractServiceAreaAdapter;
import bsi.vn.Data.ContractServiceAreaData;
import bsi.vn.Data.CookieData;
import bsi.vn.Lib.Consts;
import bsi.vn.Lib.ProcessFunc;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.content.Context;
import android.content.Intent;


@SuppressLint("ValidFragment")
public class ContractServiceAreaFragment extends Fragment {
	private Activity context;
	private int CTID;
	private ArrayList<ContractServiceAreaData> list;
	ListView lv;

	public ContractServiceAreaFragment(int cTID, Context context) {
		super();
		this.context = (Activity) context;
		CTID = cTID;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// container.removeAllViews();
		
		View tab2 = inflater.inflate(R.layout.fragment_contract_servicearea,
				container, false);
		lv=(ListView) tab2.findViewById(R.id.lvDefalt);
		myContractService myWebFetch = new myContractService();
		myWebFetch.execute(new String[] { CTID + "" });
		return tab2;
	}

	private class myContractService extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			String data = "";
			try {

				data = GetContractDetail(params[0]);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return data;
		}

		@Override
		protected void onPostExecute(String result) {
			list = new ArrayList<ContractServiceAreaData>();
			String loc_arResponse[] = result.split("\\|");
			int loc_iResponseCode = Integer.parseInt(loc_arResponse[0]);
			if (loc_iResponseCode == Consts.RC_LOGOUT) {
				startActivity(new Intent(context, LoginActivity.class));
				return;
			}
			if (loc_iResponseCode == Consts.RC_ERROR) {
				ProcessFunc.ShowSimpleDialog(context, "Error",
						loc_arResponse[1]);
				return;
			}

			try {
//				Log.d("test", loc_arResponse[1]);
				JSONArray jArray = new JSONArray(loc_arResponse[1]);
//				Log.d("test", "lengh " + jArray.length());
				for (int i = 0; i < jArray.length(); i++) {
					JSONObject json_data = jArray.getJSONObject(i);
					ContractServiceAreaData coData = new ContractServiceAreaData();
//					Log.d("test", i + "");

					coData.setnam(json_data.getString(Consts.SDB_NAME));
					coData.setcom(json_data.getInt(Consts.SDB_CONTRACTCOM));
					coData.setnot(json_data.getString(Consts.SDB_CONTRACTNOTE));
					list.add(coData);

				}
				ContractServiceAreaAdapter a = new ContractServiceAreaAdapter(context, R.layout.contract_servicearea_item, list);
				lv.setAdapter(a);
				
			} catch (JSONException e) {
				Log.e("test", "Error parsing data " + e.toString());
			}

			// lvTicket.setOnItemClickListener(new OnItemClickListener() {
			// @Override
			// public void onItemClick(AdapterView<?> parent, View view,
			// int position, long id) {
			// int TicketId = ticketData.get(position).getTicketId();
			// Intent i = new Intent(getApplicationContext(),
			// TicketDetailActivity.class);
			// i.putExtra("TicketId", TicketId);
			// startActivity(i);
			// }
			// });
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onProgressUpdate(String... text) {
		}

	}

	private String GetContractDetail(String contractID) {
		InputStream is = null;
		String result = "";
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Consts.MAIN_URL);

			CookieData cookie = ProcessFunc.GetCookie(context);

			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(4);
			nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC,
					Consts.F_CONTRACTSERVICE));
			nameValuePair.add(new BasicNameValuePair(Consts.V_USERID, String
					.valueOf(cookie.getUserId())));
			nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE, cookie
					.getCookie()));
			nameValuePair.add(new BasicNameValuePair(Consts.V_CONTRACTID, CTID
					+ ""));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "utf-8"), 16);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		} catch (Exception e) {
			Log.e("test", "Error converting result " + e.toString());
		}
		return result;
	}

}
